<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{name}}管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-select v-model="ind" placeholder="请选择图片接口模式" @change="selMode">
      <el-option v-for="item in modeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
    </el-select>
    <el-upload
      class="upload-demo"
      :action="upUrl[ind]"
      name="file_obj"
      :headers="uploadHeaders"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :on-error="handleError"
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      list-type="picture">
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传{{ind === 0 ? 'jpg/png' : 'png'}}文件</div>
    </el-upload>
    <p class="img-url" v-for="item in fileList" :key="item.uid">{{$store.state.imgUrlPix + item.response.data}}</p>
  </div>
</template>

<script>
import { uploadImage, uploadImagePng, uploadImageUrl, uploadImagePngUrl } from '../../api/userMG'
export default {
  data() {
    return {
      title: '添加',
      name: '图片接口',
      ind: 0,
      modeList: [
        {
          value: 0,
          label: '普通jpg/png图片'
        },
        {
          value: 1,
          label: '透明png专用'
        },
      ],
      upUrl: [ uploadImageUrl, uploadImagePngUrl ],
      fileList: [],
      uploadHeaders: {
        token: localStorage.getItem('logintoken')
      },
    }
  },
  // 注册组件
  components: {},
  /**
   * 创建完毕
   */
  created() {

  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    selMode(e) {
      this.ind = parseInt(e)
    },
    handleBeforeUpload(file) {
      const isImage = this.ind === 0 ? file.type.includes("image") : file.type.includes("png");
      if (!isImage) {
        let err = this.ind === 0 ? '上传文件类型必须是图片!' : '上传文件类型必须是PNG!'
        this.$message.error(err);
      }
      return isImage;
    },
    handleSuccess(res, file, fL) {
      if (res.code === 0) {
        this.fileList = fL
      } else {
        this.$message.error(res.msg)
      }
    },
    handleRemove(file, fL) {
      this.fileList = fL
    },
    handleError(err, file, fileList) {
      this.$message.error('加载失败，请稍后再试！')
    },
  }
}
</script>

<style scoped>
.el-select, .el-upload {
  margin: 15px 0;
}
.el-input {
  margin: 8px 0;
}
.img-url {
  border: 1px solid #333;
  border-radius: 10px;
  padding: 10px;
}
</style>
